﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Xml.Linq;

namespace CCRPlanner {
    public class SessionStats : INotifyPropertyChanged {
        public String SessionName { get; set; }
        public Int32 BlockLength { get; set; }
        public String Speaker { get; set; }
        public String[] Voters { get; set; }
        public Int32 Conflicts { get; set; }
        public String[] ConflictNames { get; set; }

        public String Display {
            get {
                return String.Format("{0} ({1})", SessionName, Speaker);
            }
        }

        private Int32 _block;
        public Int32 Block {
            get { return _block; }
            set {
                _block = value;
                RaisePropertyChanged("Block");
            }
        }

        public static SessionStats[] LoadSessions(String cacheFile) {

            XDocument xdoc = XDocument.Load(cacheFile);

            var ses = from s in xdoc.Descendants("Session")
                      let votes = from v in s.Element("Votes").Descendants("AttendeeID")
                                  select v.Value
                      orderby votes.Count() descending
                      select new SessionStats() {
                          SessionName = s.Element("Title").Value,
                          BlockLength = Convert.ToInt32(s.Element("BlockLength").Value),
                          Speaker = s.Element("Speaker").Value,
                          Voters = votes.ToArray()
                      };

            return ses.ToArray();
        }

        public Int32 SetConflicts(IEnumerable<SessionStats> sessions) {
            var matches = from s in sessions
                          from v in s.Voters
                          where this.Voters.Contains(v)
                          select v;

            this.Conflicts = matches.Count();

            var names = from s in sessions
                        from v in s.Voters
                        where this.Voters.Contains(v)
                        group s by s.SessionName into g
                        select String.Format("{0} - {1}", g.Count(), g.Key);

            this.ConflictNames = names.ToArray();

            RaisePropertyChanged("Conflicts");
            return this.Conflicts;
        }


        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(String prop) {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }
}
